package com.kevin.jetcache.service;

import com.kevin.jetcache.dto.CnoocTradeFlowRecord;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.util.Objects;

/**
 * @author Kevin Liu
 */
@Repository
public class CnoocTradeFlowRecordRedisDao  {

    private final RedissonClient redisson;

    private RMap<String,CnoocTradeFlowRecord> cacheMap;

    public final static String CACHE_KEY = "cnooc_order_flow_records";

    public CnoocTradeFlowRecordRedisDao(RedissonClient redisson) {
        this.redisson = redisson;
    }

    @PostConstruct
    public void init() {
        cacheMap = redisson.getMap(CACHE_KEY, new JsonJacksonCodec());
    }

    public Boolean create(CnoocTradeFlowRecord cnoocTradeFlowRecord) {
        cnoocTradeFlowRecord.setDeleted(0);
        return cacheMap.putIfAbsent(buildKey(cnoocTradeFlowRecord),cnoocTradeFlowRecord)==null;
    }

    private String buildKey(CnoocTradeFlowRecord cnoocTradeFlowRecord) {
        return cnoocTradeFlowRecord.getBusinessId()+"_" + cnoocTradeFlowRecord.getFlowType();
    }

    public void replace(CnoocTradeFlowRecord cnoocTradeFlowRecord) {
        cacheMap.replace(buildKey(cnoocTradeFlowRecord),cnoocTradeFlowRecord);
    }


    public void deleteByKey(CnoocTradeFlowRecord cnoocTradeFlowRecord) {
        cacheMap.remove(buildKey(cnoocTradeFlowRecord));
    }

    public void deleteByKey(String key) {
        cacheMap.remove(key);
    }

    public CnoocTradeFlowRecord findByFlowId(String flowId){
        return cacheMap.values().stream().filter(t->Objects.equals(t.getFlowId(),flowId)).findFirst().orElse(null);
    }

    public CnoocTradeFlowRecord findByBusinessIdAndType(Long getBusinessId,Integer type) {
        return cacheMap.values().stream().filter(t-> Objects.equals(t.getBusinessId(),getBusinessId)&&Objects.equals(t.getFlowType(),type)&&t.getDeleted() == 0)
                .findFirst().orElse(null);
    }
}
